/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package initialization;

import Database.AddressesDB;
import Database.ConfigurationDB;
import Database.UsersDB;
import Database.XMLManager.XMLAddressFiles;
import Database.XMLManager.XMLConfigurationFiles;
import Database.XMLManager.XMLUsersFile;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 *  This class is called from the Tomcat server at application startup and shutdown and take care for global objects instatiation and 
 * cleanup.
 * @author Maggioni Marcello
 */
public class ContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent arg0) {
         ServletContext app = arg0.getServletContext();
        try {
            UsersDB udb = XMLUsersFile.getDefaultInstance(app.getRealPath("") + File.separator + "database");
            AddressesDB adb = XMLAddressFiles.getDefaultInstance(app.getRealPath("") + File.separator + "database");
            ConfigurationDB cdb = XMLConfigurationFiles.getDefaultInstance(app.getRealPath("") + File.separator + "database");
            app.setAttribute("usersdb", udb);
            app.setAttribute("addressesdb", adb);
            app.setAttribute("configurationdb", cdb);
        } catch (Exception ex) {
            ex.printStackTrace(); // Print stack trace. Grave initialization error.
            System.exit(1); // Can't continue after initialization has failed. Shutting down the server.
        }
         app.setAttribute("usersmap", Collections.synchronizedMap(new HashMap<String,String>()));
    }

    public void contextDestroyed(ServletContextEvent arg0) {}

}
